<template>
  <div class="main">
    <div class="functionalArea">
      <el-button 
        v-for="item in functionalArea" 
        :key="item.name" 
        @click="showDialog(item.name)"
        size="large" 
        icon="CirclePlus" 
        type="primary">
        {{ item.name }}
      </el-button>
    </div>
    <div class="eventList">
      <div class="statistics">
        <div class="copywritingTitle">共计{{total}}个AI任务</div>
      </div>
      <el-table :data="tableData" stripe  :header-cell-style="{backgroundColor: '#f3f6f9',color:'#333',height:'50px'}" style="width: 100%">
        <el-table-column prop="TransTime" label="提交任务日期" width="180" />
        <el-table-column prop="ChatTitle" label="任务类型" width="180" />
        <el-table-column prop="Question" label="绘制指令" />
        <el-table-column label="" width="220px">
          <template #default="scope">
            <el-button  
              type="primary"
              @click="handleEdit(scope.row)"
              >查看详情</el-button
            >
            <el-button
              type="danger"
              @click="handleDelete(scope.row.Id, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <pictureDialog ref="pictureDialog" :name="name" :loading="loading" :pictureList="pictureList" v-model="dialogVisible" :Action="Action" @closeDialog="closeDialog" @submit="submit"></pictureDialog>
</template>

<script>
import axios from 'axios'
import { connrequest, getgptimage } from '../api/connrequest'
import { parseTime } from '../utils/index'
import pictureDialog from './components/pictureDialog.vue'
import answerDialog from './components/answerDialog.vue'
export default {
  components:{
    pictureDialog,
    answerDialog
  },
  data(){
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      Action: 1,
      functionalArea: [
        {name: '图片创造'},
      ],
      tableData:[],
      name: '',
      dialogVisible: false,
      loading: false,
      pictureList: []
    }
  },
  created(){
    this.getData()
  },
  methods:{
    async getData(){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          Status: 3,
          Name: sessionStorage.getItem('Name')
        }
      }
      const res = await connrequest('GetChatGPTLog', data)
      res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
      })
      
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    search(){},
    handleEdit(row){
      this.Action = 2
      this.name = '图片创造'
      this.pictureList = JSON.parse(row.Answer)
      this.dialogVisible = true
    },
    handleDelete(uuid){
      this.$confirm('删除后无法恢复，是否确认删除?', '删除任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const data = {
          Data:{
            Id: uuid
          }
        }
        const res = await connrequest('HideChatGPTLog', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    showDialog(name){
      this.Action = 1
      this.pictureList = []
      this.name = name
      this.$refs.pictureDialog.recordForm.product = ''
      this.dialogVisible = true
    },
    closeDialog(){
      this.dialogVisible = false
    },
    closeanswer(){
      this.answerDialog = false
    },  
    async submit(form){
      if(!sessionStorage.getItem('Name')){
        this.loading = false
        this.$message.error('发生错误：请先登录帐号')
        return false
      }
      if(!form.product){
        this.$message.info('图片描述为必填')
        return false
      }
      this.loading = true
      // const API_ENDPOINT = 'https://api.openai.com/v1/images/generations';
      // const OPENAI_API_KEY = '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'
      try {
        let prompt = `${form.product}`
        const gptdata = {
          Data:{
            prompt: prompt,
            n: 1,
            size: "1024x1024"
          }
        }
        const response = await getgptimage(gptdata)
        this.loading = false
        this.pictureList = response.Data.data
        const data = {
          Data:{
            Name: sessionStorage.getItem('Name'),
            ChatTitle:"图片创造",
            Question: prompt,
            Answer: JSON.stringify(this.pictureList),
            Action: 3
          }
        }
        await connrequest('WriteChatGPTLog', data)
        this.getData()
      } catch (error) {
        this.loading = false
        this.$message.error('发生错误，请重试！')
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  .main{
    width: calc(100vw - 125px);
    height: calc(100vh - 60px);
    background: #fff;
    padding: 20px;
    margin: 10px;
    .functionalArea{
      margin-bottom: 20px;
      .el-button{
        margin-right: 20px;
      }
    }
    .eventList{
      height: calc(100vh - 175px);
      overflow-y: auto;
      border: 1px solid #ebeef5;
      .statistics{
        height: 65px;
        padding: 0 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-select{
          margin-right: 10px;
        }
      }
    }
  }
</style>